package com.springboot.kafka.producer;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import static com.springboot.kafka.config.KafkaConfig.BROKER_LIST;
import static com.springboot.kafka.config.KafkaConfig.TOPIC;

public class ProducerTest {


    public static void main(String[] args) {
        Properties properties = initConfig();

        KafkaProducer<String, RecordBean> producer = new KafkaProducer<>(properties);


        try {
            for (int i = 0; i < 100; i++) {

                ProducerRecord<String, RecordBean> record = new ProducerRecord<>(TOPIC, new RecordBean("小a", i));
                /*Future<RecordMetadata> metadataFuture = producer.send(record);
                RecordMetadata metadata = metadataFuture.get();
                System.out.println(metadata.toString());*/

                producer.send(record, (m, e) -> {
                    if (e != null) {
                        System.out.println("发生失败，可重试n次");
                        producer.send(record);
                    }
                    if (m != null) {
                        System.out.println("发送成功！可记录情况");
                        //log(m)
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
       /* } catch (ExecutionException e) {
            e.printStackTrace();*/
        }finally {
            producer.close();
        }


    }

    private static  Properties initConfig(){
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //自定义序列化器
        //properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, RecordBeanSerializer.class.getName());

        //指定自定义分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, DemoPartitioner.class.getName());

        //自定义消息拦截器
        properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, DemoInterceptor.class.getName());

        //失败重试次数  可以避免可重试异常
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        //重试间隔 ms
        properties.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, "100");

        //成功接收的分区数 才算发送成功
        properties.put(ProducerConfig.ACKS_CONFIG, "1");

        properties.put(ProducerConfig.CLIENT_ID_CONFIG, "demo1");
        return properties;
    }
}
